package com.cqjtu.store.order.service.impl;

import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.order.mapper.OrderMapper;
import com.cqjtu.store.order.pojo.entity.Order;
import com.cqjtu.store.order.pojo.entity.OrderItem;
import com.cqjtu.store.order.pojo.vo.OrderItemVO;
import com.cqjtu.store.order.pojo.vo.OrderVO;
import com.cqjtu.store.order.service.OrderService;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ProjectName: cqjtu-store
 * @Titile: OrderServiceImpl
 * @Author: Lucky
 * @Description: 订单业务类
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public List<OrderVO> getList(Integer status,UserLoginVO userLoginVO) {
        List<OrderVO> orderList = orderMapper.getOrderList(status,userLoginVO.getId());
        if(orderList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"此用户没有订单数据");
        }
        Integer totalPrice = 0;
        for (OrderVO orderVO : orderList) {
            List<OrderItemVO> orderItemList = orderMapper.getOrderItemList(orderVO.getId());
            for (OrderItemVO orderItemVO : orderItemList) {
                totalPrice += (Integer)(orderItemVO.getPrice() * orderItemVO.getNum());
            }
            orderVO.setOrderItemVOList(orderItemList);
            orderVO.setTotalPrice(totalPrice);
        }
        return orderList;
    }


    @Override
    public void setStatus(Integer id,Integer status, UserLoginVO userLoginVO){
        Order order = orderMapper.getById(id);
        if (order == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "订单不存在");
        }
        if(order.getUserId() != userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "无操作权限");
        }
        int result = orderMapper.setStatus(id,status);
        if (result == 0) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "更改订单状态失败");
        }
    }
}
